import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:dio/dio.dart';
import 'package:flutter_yres/model/shop/wuliao_list_model.dart';
import 'package:flutter_yres/pages/shop/shop_detail_page.dart';
import 'package:flutter_yres/model/shop/hdk_list_model.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';

class WuLiaoPage extends StatefulWidget {
  String material_id;
  String title;
  WuLiaoPage({Key key, this.material_id, this.title}) : super(key: key);

  @override
  _WuLiaoPageState createState() => _WuLiaoPageState();
}

class _WuLiaoPageState extends State<WuLiaoPage> {
  List<WLListModelData> shopData = []; //商品列表
  int page_no = 1;
  EasyRefreshController _controller = new EasyRefreshController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Container(
          color: Colors.white,
          child: _buildSub(),
        ));
  }

  //其他类别主页内容
  Widget _buildSub() {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return Container(
      color: f0Color,
      child: new EasyRefresh(
        //刷新  加载组件
        controller: _controller,
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        header: MaterialHeader(),
        footer: MaterialFooter(),
        child: CustomScrollView(slivers: <Widget>[
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(10)) / 2,
              mainAxisSpacing: 10.0,
              crossAxisSpacing: 15.0,
              childAspectRatio: 0.6, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return shopData.length > 0
                    ? getItemContainer(context, index)
                    : Container();
              },
              childCount: shopData.length,
            ),
          ),
        ]),
        onRefresh: () async {
          page_no = 1;
          getTBKShopList();
        },
        onLoad: () async {
          page_no++;
          getTBKShopList();
        },
      ),
    );
  }

  //条件筛选头部
  _buildPopHeader() {
    return Container(
      height: ScreenUtil.getInstance().setHeight(60),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "综合",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "销量",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "价格",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "佣金",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
        ],
      ),
    );
  }

//商品单个cell
  getItemContainer(BuildContext context, int index) {
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(
            text: '¥',
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24))),
        TextSpan(
            text: shopData[index].zk_final_price,
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(28))),
        TextSpan(
          text: shopData[index].reserve_price,
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(24),
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );

    var quanHeader = Container(
      width: ScreenUtil.getInstance().setWidth(40),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_header.png"),
          fit: BoxFit.cover,
        ),
      ),
    );

    var quan = Container(
      width: ScreenUtil.getInstance().setWidth(70),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_footer.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
          child: Text(
        shopData[index].coupon_amount == null
            ? '0元'
            : shopData[index].coupon_amount + '元',
        style: TextStyle(color: Colors.white, fontSize: 10),
      )),
    );

    return GestureDetector(
        onTap: () {
          HDKListModelData model = new HDKListModelData();
          WLListModelData data = shopData[index];
          model.itemid = data.item_id;
          // print('https:'+shopData[index].pict_url);
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) =>
                      ShopDetailPage(hdkmodel: model) //打开第二个页面，并传值，传递值的名称是model
                  ));
        },
        child: Container(
            color: Colors.white,
            margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(10), 0, ScreenUtil.getInstance().setWidth(10), 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Image.network(
                  'https:' + shopData[index].pict_url,
                  width: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                  height: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                ),
                Text(
                  shopData[index].title,
                  maxLines: 2,
                  style:
                      TextStyle(fontSize: ScreenUtil.getInstance().setSp(26)),
                ),
                Container(
                  margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                  child: price,
                ),
                Container(
                  margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                  child: Text('已售' + shopData[index].volume,
                      style: TextStyle(fontSize: 12.0, color: Colors.grey)),
                ),
                Container(
                  margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: Row(
                          children: <Widget>[quanHeader, quan],
                        ),
                      ),
                      // Expanded(flex: 2, child: yongjin)
                    ],
                  ),
                )
              ],
            )));
  }

  @override
  void initState() {
    getTBKShopList();
    super.initState();
  }

  /*获取淘宝客商品列表（新）*/
  //GetTBDgOptimusMaterialUrl
  getTBKShopList() async {
    FormData data = new FormData.fromMap(
        {'material_id': widget.material_id, 'per': 8, 'p': page_no});
    Response<String> response =
        await HttpUtil().post(Api.GetTBDgOptimusMaterialUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap['data']);
    WLListModelEntity itemEntity = new WLListModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          if (page_no == 1) {
            shopData.clear();
            shopData = itemEntity.data;
            _controller.finishRefresh();
          } else {
            shopData.addAll(itemEntity.data);
            _controller.finishLoad();
          }
        });
      }
    }
  }
}
